`define WAIT 2'd0
`define START 2'd1
`define RECV 2'd2
`define FINISHING 2'd3

module recv(
input  clk, rst, iocs,
input iorw, recvrateen,
input [1:0] ioaddr,
input rxd,
output rda,  
output [7:0] recbuf
);

//so, how are we going to figure out 

reg syncff;
reg [7:0] shiftreg;
reg [7:0] holdreg;
reg [3:0] lvlcount;  //for counting the number of zeroes or ones
reg [3:0] samplenum;	//for keeping track of which sample we're on
reg [2:0] bitnum;		//for keeping track of which bit we're on
reg [1:0] status;
reg dataavail;
wire nextbit;

always @(posedge clk) begin
	if(rst)
		syncff <= 1'b1;
	else
		syncff <= rxd;
end

always @(posedge clk) begin
	if (rst)
		status <= `WAIT;
	else if (recvrateen) begin
		if (status == `WAIT) begin
			if (!syncff) begin
				status <= `START;
			end
		end 

		if ((status == `START) & (samplenum == 4'd15)) begin
			if (lvlcount < 8)
				status <= `RECV;
			else
				status <= `WAIT;
		end

		if ((status == `RECV) & (samplenum == 4'd15) & (bitnum == 3'd7)) begin
			status <= `FINISHING;
		end

		if ((status == `FINISHING) & (samplenum == 4'd15)) begin
			if (lvlcount >= 8)
				status <= `WAIT;
			else
				status <= `FINISHING; //should we discard this packet (it's bad)
		end
	end
end

always @(posedge clk) begin
	if (rst)
		bitnum <= 3'd0;
	else if (recvrateen) begin
		if (status == `RECV) begin
			if (samplenum == 4'd15)
				bitnum <= bitnum + 3'd1;
		end else
			bitnum <= 3'd0;
	end
end




always @(posedge clk) begin
   	if (rst)
		shiftreg <= 8'b11111111;
	else if (recvrateen) begin
		if (status == `RECV & samplenum == 4'd15)
			shiftreg <= {nextbit, shiftreg[7:1]};
	end
end

always @(posedge clk) begin
   	if (rst)
		holdreg <= 8'd0;
	else if (recvrateen) begin
		if ((status == `FINISHING) & (samplenum == 4'd15)) //check lvlcount for good final bit?
			holdreg <= shiftreg;
	end
end	

always @(posedge clk) begin
	if (rst)
		dataavail <= 1'b0;
	else if (recvrateen & (status == `FINISHING) & (samplenum == 4'd15))
		dataavail <= 1'b1;
	else if (iorw && iocs && (ioaddr == 2'b00))
		dataavail <= 1'b0;
end
	  
always @(posedge clk) begin
	if (rst)
		lvlcount <= 4'd0;
	else	if (recvrateen) begin
		if  (status == `WAIT | samplenum == 4'd15)
			lvlcount <= 4'd0;
		else
			lvlcount <= lvlcount + syncff;
	end
end

always @(posedge clk) begin
	if (rst)
		samplenum <= 4'd0;
	else	if (recvrateen) begin
		if  (status == `WAIT)
			samplenum <= 4'd0;
		else
			samplenum <= samplenum + 1;
	end
end

assign rda = dataavail;
assign recbuf = holdreg;
assign  nextbit = (lvlcount < 8) ? 1'b0 : 1'b1;
endmodule

